package com.hamilton.erik.pt.mobile.android.app;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;

public class MultiTaskProgressDialog extends ProgressDialog {

	private ArrayList<String> currentTasks = new ArrayList<String>();
	private boolean visible = false;
	
	public MultiTaskProgressDialog(Context context, String title) {
		super(context);
		setTitle(title);
	}

	public MultiTaskProgressDialog(Context context, String title, int theme) {
		super(context, theme);
		setTitle(title);
	}

	@Override
	public void show() {
		if(!visible) {
			super.show();
			visible = true;
		}
	}
	
	@Override
	public void dismiss() {
		if(currentTasks.isEmpty()) {
			visible = false;
			super.dismiss();
		}
	}
	
	public void addMessage(String message) {
		if(!currentTasks.contains(message)) {
			currentTasks.add(message);
			updateMessageDisplay();
		}
	}
	
	public void dismissMessage(String message) {
		if(currentTasks.contains(message)) {
			currentTasks.remove(message);
			if(currentTasks.isEmpty()) {
				super.dismiss();
			}
			else {
				updateMessageDisplay();
			}
		}
	}
	
	private void updateMessageDisplay() {
		if(currentTasks.isEmpty()) {
			super.dismiss();
		}
		else {
			StringBuilder message = new StringBuilder();
			
			for(int i = 0; i < currentTasks.size(); i++) {
				if(i != 0) {
					message.append("\n");
				}
				
				message.append(currentTasks.get(i));
			}
			
			super.setMessage(message.toString());
		}
	}
}
